package com.dt.ops;

import com.dt.module.om.Command;
import com.dt.module.om.client.ClientGUI;
import com.dt.module.om.term.entity.Machine;
import com.dt.module.om.util.*;
import org.apache.commons.cli.*;
import org.apache.commons.net.ftp.FTPClient;

import java.awt.*;
import java.io.*;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {

	static ArrayList<Machine> nodes = new ArrayList<Machine>();
	public static Command cmds = new Command();
	public static Options options = new Options();
	public static String nodeconf = "base.node";
	public static String cmdconf = "cmd.conf";
	public static String cmdstr = "show";
	public static String sftpsfile = "sfile";
	public static String sftpdfiledir = "dfiledir";
	public static String sftpdfilename = "dfilename";
	public static String sd = "sd";
	public static String sf = "sf";
	public static boolean pwdentr=false;
	public static void load() {
		nodes = ToolUtil.readHostConf(nodeconf);
		if (cmdstr.equals("action") || cmdstr.equals("show")) {
			cmds = ToolUtil.readCmdConf(cmdconf);
		}

	}
	private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
	public static String toHexString(byte[] data) {
		StringBuilder r = new StringBuilder(data.length * 2);
		for (byte b : data) {
			r.append(hexCode[(b >> 4) & 0xF]);
			r.append(hexCode[(b & 0xF)]);
		}
		return r.toString();
	}
	public static String getMD5(File file) {
		FileInputStream fileInputStream = null;
		try {
			MessageDigest MD5 = MessageDigest.getInstance("MD5");
			fileInputStream = new FileInputStream(file);
			byte[] buffer = new byte[8192];
			int length;
			while ((length = fileInputStream.read(buffer)) != -1) {
				MD5.update(buffer, 0, length);
			}
			return toHexString(MD5.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (fileInputStream != null){
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static int exec() {
		DateFormat normalDf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		load();
		if (cmdstr.equals("show")) {
			System.out.println("Show Node List:");
			for (int i = 0; i < nodes.size(); i++) {
				System.out.println("	"+nodes.get(i));
			}
			System.out.println("	Total Nodes:" + nodes.size());
			System.out.println("Upload Command List:");
			for (int i = 0; i < cmds.upload.size(); i++) {
				System.out.println("	"+cmds.upload.get(i));
			}
			System.out.println("Execute Command List:");
			for (int i = 0; i < cmds.cmds.size(); i++) {
				System.out.println("	"+cmds.cmds.get(i));
			}
			System.out.println("DownLoad Command:");
			for (int i = 0; i < cmds.download.size(); i++) {
				System.out.println("	"+cmds.download.get(i));
			}
			System.out.println("\n\n\n\n");

		} else if (cmdstr.equals("check")) {
			System.out.println("###########Check Start#########");
			for (int i = 0; i < nodes.size(); i++) {
				Machine machine = nodes.get(i);
				System.out.println(machine);
				RemoteShellExecutor executor = new RemoteShellExecutor(machine.getHostname().trim(), machine.getUsername().trim(),
						machine.getPassword(), machine.getPort());
				String cmds = "echo 'Success!';hostname";
				RemoteShellResult r2 = executor.exec(cmds);
				r2.print();
				nodes.get(i).setCt(r2.result);
				executor.close();
			}
			writeCTOut(nodes);
			System.out.println("###########Check End###########");
		} else if (cmdstr.equals("action")) {
			Date sdate = new Date();
			String sdateStr=normalDf1.format(sdate);
			System.out.println("Ops Exucute start,Time"+sdateStr);
			if (cmds!=null&&cmds.cmds.size() > 0) {
				for (int i = 0; i < nodes.size(); i++) {
					Machine machine = nodes.get(i);
					System.out.println("-------------------------------------------------------------------------------------------");
					System.out.println("Index:"+(i+1)+",Node:"+machine.getHostname()+"");
					System.out.println("	Detail:"+machine);
					SftpClient sftp = new SftpClient(machine);
					sftp.connect();
					if(!sftp.isConnected()){
						System.out.println("Connect to host error!");
						continue;
					}
					RemoteShellExecutor executor = new RemoteShellExecutor(machine.getHostname().trim(), machine.getUsername().trim(), machine.getPassword(), machine.getPort());
					System.out.println("  Process Upload:");
					for(int j=0;j<cmds.upload.size();j++){
						System.out.println("	Upload:"+cmds.upload.get(j));
						String[] us=cmds.upload.get(j).split("@@");
						String sf="";
						String dd="";
						String df="";
						if(us.length==3){
							sf=us[0].split("=")[1].trim();
							dd=us[1].split("=")[1].trim();
							df=us[2].split("=")[1].trim();
							System.out.println("		Parse success,"+"sf="+sf+",dd="+dd+",df="+df);
						}else{
							System.out.println("		Parse error,length is not 3");
						}
						sftp.changeDirectory(dd);
						try {
							if("/tmp".equals(sftp.getCurrentCatalog())){
								System.out.println("	delete file "+df +" start");
								sftp.deleteFile(df);
								System.out.println("	delete file success");
							}
						} catch (IOException e) {
							System.out.println("	delete file error,detail:"+e.getMessage());
						}
						sftp.uploadFile(new File(sf), df, null);
					}
					System.out.println("  Process Execute Show");
					HashMap<String,String> map=machine.getKvmap();
					ArrayList<String> ecmds = new ArrayList<String>();
					for(int k=0;k<cmds.cmds.size();k++){
						String s=cmds.cmds.get(k);
						Iterator iter = map.keySet().iterator();
						while (iter.hasNext()) {
							String key = (String) iter.next();
							String val = map.get(key);
							s=s.replaceAll("##"+key+"##",val);
						}
						s=s.replaceAll("##ip##",machine.getHostname().trim()).replaceAll("##host_user##",machine.getUsername().trim());
						ecmds.add(s);
					}
					//重写ecmds 执行
					for(int c=0;c<ecmds.size();c++){
						System.out.println("	"+ecmds.get(c));
					}
					//#####################create execute method start###############
					System.out.println("  OpsAutoExecute");
					String execfilepath="";
					String execfilename="auto_ops_execute.sh";
					File temp=null;
					try {
						temp = File.createTempFile("opsexecute", ".sh");
						execfilepath=temp.getAbsolutePath();
						BufferedWriter out = new BufferedWriter(new FileWriter(temp));
						for(int c=0;c<ecmds.size();c++){
							out.write(ecmds.get(c)+"\n");
						}
						out.close();
					} catch (IOException e) {
						System.out.println("	create tempfile error,info:"+e.getMessage());
						e.printStackTrace();
					}
					sftp.changeDirectory("/tmp");
					try {
						if("/tmp".equals(sftp.getCurrentCatalog())){
							System.out.println("	delete temp execute file "+execfilename+" start ");
							sftp.deleteFile(execfilename);
							System.out.println("	delete temp execute file success");
						}
					} catch (IOException abc) {
						System.out.println("	delete temp execute file error,detail:"+abc.getMessage());
					}
					sftp.uploadFile(temp, execfilename, null);
					ArrayList<String> change_ecmds = new ArrayList<String>();
					change_ecmds.add("sed -i \"s/^M//\" /tmp/"+execfilename);
					change_ecmds.add("sh /tmp/"+execfilename);
					RemoteShellResult r2 = executor.exec(change_ecmds);
					r2.print();
					nodes.get(i).setCt(r2.result);
					//RemoteShellResult r2 = executor.exec(ecmds);
					//r2.print();
					//nodes.get(i).setCt(r2.result);
				    //#####################create execute method end###############
					System.out.println("  Process Download");
					for(int j=0;j<cmds.download.size();j++){
						System.out.println("	Download:"+cmds.download.get(j));
						String[] us=cmds.download.get(j).split("@@");
						String sf="";
						String dd="";
						String df="";
						if(us.length==3){
							sf=us[0].split("=")[1].trim();
							dd=us[1].split("=")[1].trim();
							df=us[2].split("=")[1].trim();
							System.out.println("		Parse success,"+"sf="+sf+",dd="+dd+",df="+df);
						}else{
							System.out.println("		Parse error,length is not 3");
						}
						sftp.downloadFile(sf, dd + File.separator+df);
					}
					sftp.close();
					executor.close();
				}
				writeCTOut(nodes);
			} else {
				System.out.println("Error,Command Line List is Empty.");
			}

			Date edate = new Date();
			String edateStr=normalDf1.format(sdate);
			System.out.println("Ops Exucute finish,Time:"+edateStr+",Run Time:"+timeXC(sdate,edate));
		} else if (cmdstr.equals("sftpupload")) {
			System.out.println("###########SftpUpload Start#########");
			for (int i = 0; i < nodes.size(); i++) {
				Machine machine = nodes.get(i);
				System.out.print(machine + "\n");
				System.out.println("Upload Source:" + sftpsfile + ",Dest:" + sftpdfiledir + File.separator + sftpdfilename);
				SftpClient sftp = new SftpClient(machine);
				sftp.connect();
				sftp.changeDirectory(sftpdfiledir);
				sftp.uploadFile(new File(sftpsfile), sftpdfilename, null);
			}
			System.out.println("###########Sftp End###############");

		} else if (cmdstr.equals("sftpdownload")) {
			System.out.println("###########SftpDownload Start#########");
			for (int i = 0; i < nodes.size(); i++) {
				Machine machine = nodes.get(i);
				System.out.print(machine + "\n");
				System.out.println("Download Source:" + sftpsfile + ",Dest:" + sftpdfiledir + File.separator + sftpdfilename);
				SftpClient sftp = new SftpClient(machine);
				sftp.connect();
				sftp.downloadFile(sftpsfile, sftpdfiledir + File.separator + sftpdfilename);
			}
			System.out.println("###########Sftp End###############");
		} else if (cmdstr.equals("ftpupload")) {
			System.out.println("###########ftpUpload Start#########");
			for (int i = 0; i < nodes.size(); i++) {
				Machine machine = nodes.get(i);
				System.out.println("Node:"+machine.getHostname());
				Date sdate = new Date();
				String sdateStr=normalDf1.format(sdate);
				System.out.println("start time:"+sdateStr);
				System.out.println("Upload Source:" + sftpsfile + ",Dest:" + sftpdfiledir + File.separator + sftpdfilename);
				FTPUtil f = new FTPUtil();
				File file=new File(sftpsfile);
				if(file.isFile()&&file.exists()){
					FTPClient ftp = f.getFTPClient(machine.getHostname(), machine.getPort(),machine.getUsername(),machine.getPassword());
					f.uploadFile(ftp, sftpsfile, sftpdfiledir);
					f.closeFTP(ftp);
				}else{
					System.out.println("error,sourcefile is not exist");
				}
				Date edate = new Date();
				String edateStr=normalDf1.format(sdate);
				System.out.println("end time:"+edateStr);
				System.out.println("time:"+timeXC(sdate,edate));

			}
			System.out.println("###########ftp End###############");

		} else if (cmdstr.equals("ftpdownload")) {
			System.out.println("###########ftpDownload Start#########");
			for (int i = 0; i < nodes.size(); i++) {
				Machine machine = nodes.get(i);
				System.out.println("Node:"+machine.getHostname());
				Date sdate = new Date();
				String sdateStr=normalDf1.format(sdate);
				System.out.println("start time:"+sdateStr);
				System.out.println("Download Source:" + sd+File.separator+sf+",Dest_dir:"+sftpdfiledir);
				FTPUtil f = new FTPUtil();
				FTPClient ftp = f.getFTPClient(machine.getHostname(), machine.getPort(),machine.getUsername(),machine.getPassword());
				f.downLoadFTP(ftp, sd, sf, sftpdfiledir);
				f.closeFTP(ftp);
				Date edate = new Date();
				String edateStr=normalDf1.format(sdate);
				System.out.println("end time:"+edateStr);
				System.out.println("time:"+timeXC(sdate,edate));
			}
			System.out.println("###########ftp End###############");
		}
		return 0;
	}

	public static String timeXC(Date d1,Date d2){
		String res="";
		//毫秒ms
		long diff = d2.getTime() - d1.getTime();
		long diffSeconds = diff / 1000 % 60;
		long diffMinutes = diff / (60 * 1000) % 60;
		long diffHours = diff / (60 * 60 * 1000) % 24;
		long diffDays = diff / (24 * 60 * 60 * 1000);
//		System.out.print("两个时间相差：");
//		System.out.print(diffDays + " 天, ");
//		System.out.print(diffHours + " 小时, ");
//		System.out.print(diffMinutes + " 分钟, ");
//		System.out.print(diffSeconds + " 秒.");
		res=diffHours+"小时"+diffMinutes+"分"+diffSeconds+"秒";
		return res;
	}
	public static void writeCTOut(ArrayList<Machine> hosts) {
		File fout = new File("out.txt");
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			fos = new FileOutputStream(fout);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
			for (int i = 0; i < hosts.size(); i++) {
				String h="";
				if(hosts.get(i).getHostname()!=null){
					h=hosts.get(i).getHostname();
				}
				String ct="";
				if(hosts.get(i).getCt()!=null){
					ct=hosts.get(i).getCt().trim();
				}else{
					ct="ct is null";
				}
				bw.write("###########" + h + "###########\n" +ct );
				bw.newLine();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (bw != null)
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}


	public static void help() {
		HelpFormatter formatter = new HelpFormatter();
		formatter.setWidth(125);
		formatter.setDescPadding(2);
		formatter.setLeftPadding(6);
		formatter.setSyntaxPrefix("Usage:");
		formatter.printHelp("java -jar ops.jar", options, true);
		System.out.println("Priority:");
		System.out.println("	help-->version-shellgui-sftp-batchops");
		System.out.println("Example:");
		System.out.println("	java -jar ops.jar [-pwden] -e show -n base.node -c cmd.conf ");
		System.out.println("	java -jar ops.jar [-pwden] -n base.node -sftp upload    -s  /tmp/source.file  -df dest.file -dd /tmp");
		System.out.println("	java -jar ops.jar [-pwden] -n base.node -sftp download  -s  /tmp/file.txt     -df dest.file -dd /tmp");
		System.out.println("	java -jar ops.jar [-pwden] -n base.node -ftp  upload    -s  /tmp/source.file  -df dest.file -dd /tmp");
		System.out.println("	java -jar ops.jar [-pwden] -n base.node -ftp  download  -sd /tmp              -sf ftp.txt   -dd /tmp");
		System.out.println("	java -jar ops.jar -unzip -sf /tmp/file.zip -dd /tmp");
		System.out.println("	java -jar ops.jar -m /tmp/neetMD5File.txt");
		System.out.println("	java -jar ops.jar -portcheck");
		System.out.println("	java -jar ops.jar -en something ");
		System.out.println("	java -jar ops.jar -rcpr -ua root -ha 192.168.1.1 -pa 123456 -porta 22 -rpath /tmp/a.tar -ub root -hb 192.168.1.2 -pb 123456 -portb 22 -upath /tmp/b.tar");
		System.out.println("	java -jar ops.jar -yml /tmp/application.yml -k redis.name -v value");
		System.out.println("	java -jar ops.jar -t +1");
		System.out.println("	java -jar ops.jar -g ");
		System.out.println("	java -jar ops.jar -v ");
		System.out.println("	java -jar ops.jar -h ");
		//System.out.println("	java -jar ops.jar -now -format mm-dd-hh");
	}

	public static void main(String[] args) {
		try {
			execute(args);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			System.out.println("ParseException");
		}
	}

	public static void execute(String[] args) throws ParseException {
		System.setProperty("java.util.logging.config.file", "ops.properties");
		// boolean型的option
		options.addOption(
				Option.builder("v").longOpt("version").type(String.class).desc("show version and exit").build());
		options.addOption(Option.builder("h").longOpt("help").type(String.class).desc("show help").build());

		options.addOption(Option.builder("t").hasArg(true).longOpt("time").type(String.class).desc("show time yyyy-mm-dd,+1 or -1 or 0").build());
		options.addOption(Option.builder("e").hasArg(true).longOpt("exec").type(String.class)
				.desc("set the execute type,support type is show,check,action").build());
		options.addOption(Option.builder("g").hasArg(false).longOpt("shellgui").type(String.class)
				.desc("start a simple ssh client").build());

		options.addOption(Option.builder("m").hasArg(true).longOpt("md5").type(String.class)
				.desc("show file md5 value").build());

		options.addOption(Option.builder("n").hasArg(true).longOpt("node").type(String.class)
				.desc("set configuration file of node describe(default: base.node)").build());
		options.addOption(Option.builder("c").hasArg(true).longOpt("cmd").type(String.class)
				.desc("set configuration file of command describe(default: cmd.conf)").build());

		options.addOption(Option.builder("sftp").hasArg(true).longOpt("sftp").type(String.class)
				.desc("the sftp function,support type is upload,download").build());

		options.addOption(Option.builder("sd").hasArg(true).longOpt("src_dir").type(String.class)
				.desc("the sftp/ftp source directory").build());


		options.addOption(Option.builder("sf").hasArg(true).longOpt("src_filename").type(String.class)
				.desc("the sftp/ftp source filename").build());


		options.addOption(Option.builder("s").hasArg(true).longOpt("src_path").type(String.class)
				.desc("the sftp/ftp source file").build());

		options.addOption(Option.builder("df").hasArg(true).longOpt("dest_filename").type(String.class)
				.desc("the sftp/ftp destination filename").build());

		options.addOption(Option.builder("dd").hasArg(true).longOpt("dest_dir").type(String.class)
				.desc("the sftp/ftp destination directory").build());

		options.addOption(Option.builder("ftp").hasArg(true).longOpt("ftp").type(String.class)
				.desc("the ftp function,support type is upload,download").build());

		options.addOption(Option.builder("portcheck").hasArg(false).longOpt("portcheck").type(String.class)
				.desc("edit rule to check port is open or not").build());

		options.addOption(Option.builder("fil").hasArg(false).longOpt("filter").type(String.class)
		.desc("keyword ULIMIT to skip "+ToolUtil.filCommandList.toString()).build());

		options.addOption(Option.builder("en").hasArg(true).longOpt("encryption").type(String.class)
				.desc("encrypted string").build());

		options.addOption(Option.builder("unzip").hasArg(false).longOpt("unzipfile").type(String.class)
				.desc("unzip file").build());

		options.addOption(Option.builder("pwden").hasArg(false).longOpt("pwden").type(String.class)
				.desc("if encrypted ftp/sftp/ssh").build());

		options.addOption(Option.builder("yml").hasArg(false).longOpt("yml").type(String.class)
				.desc("modify yml value").build());



		options.addOption(Option.builder("rcpr").hasArg(false).longOpt("rcpr").type(String.class)
				.desc("scp A to scp B ").build());

		options.addOption(Option.builder("ua").hasArg(true).longOpt("userA").type(String.class)
				.desc("userA").build());
		options.addOption(Option.builder("ha").hasArg(true).longOpt("hostA").type(String.class)
				.desc("hostA").build());
		options.addOption(Option.builder("pa").hasArg(true).longOpt("passwordA").type(String.class)
				.desc("passwordA").build());
		options.addOption(Option.builder("porta").hasArg(true).longOpt("porta").type(String.class)
				.desc("porta").build());
		options.addOption(Option.builder("rpath").hasArg(true).longOpt("fileRemotePath").type(String.class)
				.desc("fileRemotePath").build());
		options.addOption(Option.builder("ub").hasArg(true).longOpt("userB").type(String.class)
				.desc("userA").build());
		options.addOption(Option.builder("hb").hasArg(true).longOpt("hostB").type(String.class)
				.desc("hostA").build());
		options.addOption(Option.builder("pb").hasArg(true).longOpt("passwordB").type(String.class)
				.desc("passwordA").build());
		options.addOption(Option.builder("portb").hasArg(true).longOpt("portb").type(String.class)
				.desc("porta").build());
		options.addOption(Option.builder("upath").hasArg(true).longOpt("fileUploadPath").type(String.class)
				.desc("fileUploadPath").build());




		CommandLineParser parser = new DefaultParser();
		CommandLine cmd = parser.parse(options, args);

		if(cmd.hasOption("pwden")){
			pwdentr=true;
		}

		// 询问是否有help
		if (cmd.hasOption("h")) {
			// 调用默认的help函数打印
			help();
			return;
		}
		// 查看版本
		if (cmd.hasOption("v")) {
			System.out.println("ops version: ops/1.3.9");
			return;
		}
		// 时间
		if (cmd.hasOption("t")) {
			String str = cmd.getOptionValue("t", "0");
			Date date = new Date();
			if(str.startsWith("+")){
				 Calendar c=new GregorianCalendar();
				 c.setTime(date);
				 c.add(c.DATE,Integer.valueOf(str.replace("+","")));
				 date=c.getTime();
			}else if(str.startsWith("-")){
				Calendar c=new GregorianCalendar();
				c.setTime(date);
				c.add(c.DATE,-1*Integer.valueOf(str.replace("-","")));
				date=c.getTime();
			}
			SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
			System.out.println(format.format(date));
			return;
		}

		if (cmd.hasOption("g")) {
			SwingShell client = new SwingShell();
			client.startGUI();
			return;
		}
		if (cmd.hasOption("portcheck")) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						ClientGUI frame = new ClientGUI();
						frame.setSize(800, 600);
						frame.setVisible(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			return;
		}
		if (cmd.hasOption("unzip")) {
			String sf = cmd.getOptionValue("sf", "none.zip");
			String dd = cmd.getOptionValue("dd", "/tmp");
			System.out.println("start to unzip str");
			ZipUtil.unzipFile(sf,dd);
			return ;
		}
		if (cmd.hasOption("en")) {
			String str = cmd.getOptionValue("en", "none");
			String res="";
			DES des = null;
			try {
				des = new DES();
				res=des.encrypt(str);
				System.out.println(res);
			} catch (Exception e) {
				System.out.println("encrypt/decrypt error "+e.getMessage());
			}
			return ;
		}

		if (cmd.hasOption("m")) {
			String cmdstr = cmd.getOptionValue("m", "md5.txt");
			File f=new File(cmdstr);
			if(f.exists()){
				System.out.println(getMD5(f).toLowerCase());
			}else{
				System.out.println("none");
			}
			return;
		}

		if (cmd.hasOption("n")) {
			nodeconf = cmd.getOptionValue("n", "base.node");
		}

		if (cmd.hasOption("c")) {
			cmdconf = cmd.getOptionValue("c", "cmd.conf");
		}


		if (cmd.hasOption("s")) {
			sftpsfile= cmd.getOptionValue("s", "/tmp/source.txt");
		}


		if (cmd.hasOption("sd")) {
			sd = cmd.getOptionValue("sd", "/tmp");
		}


		if (cmd.hasOption("sf")) {
			sf = cmd.getOptionValue("sf", "ftp.txt");
		}


		if (cmd.hasOption("df")) {
			sftpdfilename = cmd.getOptionValue("df", "dest.txt");
		}
		if (cmd.hasOption("dd")) {
			sftpdfiledir = cmd.getOptionValue("dd", "/tmp");
		}


		if (cmd.hasOption("sftp")) {
			String sftp = cmd.getOptionValue("sftp", "download");
			if (sftp.equals("upload")) {
				cmdstr = "sftpupload";
			} else {
				cmdstr = "sftpdownload";
			}
			exec();
			return;
		}

		if (cmd.hasOption("ftp")) {
			String sftp = cmd.getOptionValue("ftp", "download");
			if (sftp.equals("upload")) {
				cmdstr = "ftpupload";
			} else {
				cmdstr = "ftpdownload";
			}
			exec();
			return;
		}

		if (cmd.hasOption("e")) {
			cmdstr = cmd.getOptionValue("e", "show");
			if (!(cmdstr.equals("check") || cmdstr.equals("action") || cmdstr.equals("show"))) {
				cmdstr = "show";
			}
			exec();
			return;
		}

		if (cmd.hasOption("rcpr")) {
			String ua= cmd.getOptionValue("ua", "");
			String ha= cmd.getOptionValue("ha", "");
			String pa= cmd.getOptionValue("pa", "");
			String porta= cmd.getOptionValue("porta", "22");
			String rpath= cmd.getOptionValue("rpath", "");
			String ub= cmd.getOptionValue("ub", "");
			String hb= cmd.getOptionValue("hb", "");
			String pb= cmd.getOptionValue("pb", "");
			String portb= cmd.getOptionValue("portb", "22");
			String upath= cmd.getOptionValue("upath", "");
			FileTransfer.scp(ua,ha,pa,Integer.parseInt(porta),rpath,ub,hb,pb,Integer.parseInt(portb),upath);
			return;
		}
		help();
	}

}
